﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo.Wmi;

namespace SqlFileLayoutViewer {
    class SqlInstanceDiscovery {
        public static List<String> DiscoverInstances() {

            // Try to list the local SQL instances when the form loads
            // If this doesn't work, no biggie
            List<String> instances = new List<string>();
      
            ManagedComputer mc = new ManagedComputer();

            mc.ConnectionSettings.ProviderArchitecture = ProviderArchitecture.Use64bit;
            if (mc.ServerInstances.Count == 0) {
                mc.ConnectionSettings.ProviderArchitecture = ProviderArchitecture.Use32bit;
            }

            foreach (Microsoft.SqlServer.Management.Smo.Wmi.ServerInstance i in mc.ServerInstances) {
                string servername = i.Name;
                if (i.Name == "MSSQLSERVER") {
                    servername = ".";
                }
                else {
                    servername = ".\\" + i.Name;
                }
                instances.Add(servername);
            }
            
            // Alternate method - requires sql browser & is a bit slow
            // System.Data.Sql.SqlDataSourceEnumerator instance = System.Data.Sql.SqlDataSourceEnumerator.Instance;
            // System.Data.DataTable table = instance.GetDataSources();

            return instances;
        }
    }
}
